src = $(wildcard src/*.cc)
obj = $(src:.cc=.o)
dep = $(obj:.o=.d)
name = goatkit
alib = lib$(name).a

so_major = 0
so_minor = 1

ifdef cfg_optim
	opt = -O3
endif
ifdef cfg_dbg
	dbg = -g
endif

CFLAGS = -pedantic -Wall $(opt) $(dbg) $(pic) -Iinclude -Isrc -I.
CXXFLAGS = $(CFLAGS)
LDFLAGS = $(libgl) -lpthread -ldl

ifeq ($(shell uname -s), Darwin)
	libgl = -framework OpenGL

	solib = lib$(name).dylib
	shared = -dynamiclib
else
	libgl = -lGL

	ldlink = lib$(name).so
	soname = $(ldlink).$(so_major)
	solib = $(soname).$(so_minor)
	shared = -shared -Wl,-soname=$(soname)
	pic = -fPIC
endif

.PHONY: all
all: static shared

.PHONY: static
static: $(alib)

.PHONY: shared
shared: $(solib)

.PHONY: themes
themes:
	$(MAKE) -C themes

.PHONY: themes-clean
themes-clean:
	$(MAKE) -C themes clean

.PHONY: themes-install
themes-install:
	$(MAKE) -C themes install

.PHONY: themes-uninstall
themes-uninstall:
	$(MAKE) -C themes uninstall

$(alib): $(obj)
	$(AR) rcs $@ $(obj)

$(solib): $(obj)
	$(CXX) -o $@ $(shared) $(obj) $(LDFLAGS)
	@[ -n "$(soname)" ] && \
		echo 'creating symlinks ...' && \
		rm -f $(soname) $(ldlink) && \
		ln -s $(solib) $(soname) && \
		ln -s $(soname) $(ldlink) || \
		true

-include $(dep)

%.d: %.c
	@$(CPP) $(CFLAGS) $< -MM -MT $(@:.d=.o) >$@

%.d: %.cc
	@$(CPP) $(CXXFLAGS) $< -MM -MT $(@:.d=.o) >$@

.PHONY: clean
clean:
	rm -f $(obj) $(solib) $(alib)

.PHONY: dep
dep:
	rm -f $(dep)

.PHONY: install
install: $(solib) $(alib) themes-install
	mkdir -p $(DESTDIR)$(PREFIX)/include/goatkit $(DESTDIR)$(PREFIX)/lib
	cp include/*.h config.h $(DESTDIR)$(PREFIX)/include/goatkit/
	cp $(alib) $(DESTDIR)$(PREFIX)/lib/$(alib)
	cp $(solib) $(DESTDIR)$(PREFIX)/lib/$(solib)
	@[ -n "$(soname)" ] && \
		echo 'installing symlinks ...' && \
		cd $(DESTDIR)$(PREFIX)/lib && \
		rm -f $(soname) $(ldlink) && \
		ln -s $(solib) $(soname) && \
		ln -s $(soname) $(ldlink) || \
		true

.PHONY: uninstall
uninstall: themes-uninstall
	rm -f $(DESTDIR)$(PREFIX)/include/goatkit/*.h
	rmdir $(DESTDIR)$(PREFIX)/include/goatkit
	rm -f $(DESTDIR)$(PREFIX)/lib/$(alib)
	rm -f $(DESTDIR)$(PREFIX)/lib/$(solib)
	@[ -n "$(soname)" ] && \
		echo 'removing symlinks ...' && \
		rm -f $(DESTDIR)$(PREFIX)/lib/$(soname) && \
		rm -f $(DESTDIR)$(PREFIX)/lib/$(ldlink) || \
		true
